//
//  OAuthViewController.swift
//  JLWeibo
//
//  Created by sunjinliang on 15/12/7.
//  Copyright © 2015年 sunjinliang. All rights reserved.
//

import UIKit
import SVProgressHUD
class OAuthViewController: UIViewController {
    var webview = UIWebView()
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.whiteColor()
       self.webview.loadRequest(NSURLRequest(URL: NetworkTools.onceToken.oauthURl))
        
    }
    func closeOath(){
        
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    func autoFill(){
        let js = "document.getElementById('userId').value = '651082931@qq.com';" +
        "document.getElementById('passwd').value = 'a123liangliang';"
        webview.stringByEvaluatingJavaScriptFromString(js)
    }
    
    override func loadView() {
        view = webview
        webview.delegate = self
        navigationItem.title = "登陆新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "closeOath")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        
    }
}
extension OAuthViewController : UIWebViewDelegate{
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        guard let url = request.URL where url.host == "www.baidu.com" else{
            return true
        }
        guard let _ = url.query where  ((url.query?.hasPrefix("code=")) != nil) else{
       
          return true
        }
        let code = url.query?.substringFromIndex("code=".endIndex)
    
        UserAccountVM.shareUserAccount.loadAccessToken(code!) { (isSuccessed) -> () in
            if !isSuccessed{
                print("失败了")
                //DISPATCH_TIME_NOW, Int64(delta * Double(NSEC_PER_SEC)
                SVProgressHUD.showInfoWithStatus("网络不给力稍后重试")
               dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64( 0.5 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { () -> Void in
                SVProgressHUD.dismiss()
                self.closeOath()
               })
              
            }else{
                print("成功了--------")
                self.dismissViewControllerAnimated(true, completion: { () -> Void in
                    SVProgressHUD.dismiss()
                    NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootViewControllerNotification, object: "welcome")
                })
            }
        }
    
    return false
}
}